﻿using System;

namespace Microsoft.Popfly.GameCreator.GameEngine.Behaviors
{
    public class DistancedBehavior : IBehavior
    {
        private Game m_game;
        private BehaviorOwner m_owner;
        private MotionBehavior m_behavior;
        private double m_killAfterDistance;

        public DistancedBehavior(Game game, BehaviorOwner owner, MotionBehavior behavior, double killAfterDistance)
        {
            m_game = game;
            m_owner = owner;
            m_behavior = behavior;
            m_killAfterDistance = killAfterDistance;

        }

        #region Behavior Members

        public void Invoke(BehaviorOwner sender, Microsoft.Popfly.GameCreator.GameEngine.Events.PGCEventArgs args)
        {
            // This one will keep doing the behavior every frame
            Events.EventListener removeAfterInterval = new Events.StandardListener(
                        m_game,
                        m_owner,
                        null,
                        m_behavior,
                        null,
                        null,
                        new Events.EveryFrameChecker(m_game)
                        );

            // This one will stop it from doing it every frame
            m_owner.AddBehavior(
                new Events.StandardListener(
                    m_game,
                    m_owner,
                    null,
                    new KillBehavior(m_owner, removeAfterInterval),
                    null,
                    null,
                    new Events.DistanceEventChecker(m_game, m_owner, m_behavior, m_killAfterDistance, false)
                    )
                );

            // add after the checker so that if the checker is valid we won't execute it.
            m_owner.AddBehavior(
                    removeAfterInterval
                    );
        }

        #endregion
    }
}
